from django.db import models
from django_cryptography.fields import encrypt
from django.utils import timezone
import uuid


class City(models.Model):
    name = models.CharField(max_length=100, unique=True)
    code = models.CharField(max_length=10, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class DataCenter(models.Model):
    name = models.CharField(max_length=100)
    code = models.CharField(max_length=10, unique=True)
    city = models.ForeignKey(City, on_delete=models.CASCADE, related_name='data_centers')
    address = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('name', 'city')

    def __str__(self):
        return f"{self.name} ({self.city})"


class Host(models.Model):
    OS_CHOICES = [
        ('linux', 'Linux'),
        ('windows', 'Windows'),
        ('macos', 'MacOS'),
        ('other', 'Other'),
    ]

    STATUS_CHOICES = [
        ('active', 'Active'),
        ('maintenance', 'Maintenance'),
        ('retired', 'Retired'),
    ]

    hostname = models.CharField(max_length=100, unique=True)
    ip_address = models.GenericIPAddressField(unique=True)
    os_type = models.CharField(max_length=20, choices=OS_CHOICES)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active')
    root_password = encrypt(models.CharField(max_length=200))
    data_center = models.ForeignKey(DataCenter, on_delete=models.CASCADE, related_name='hosts')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    last_password_change = models.DateTimeField(default=timezone.now)
    is_reachable = models.BooleanField(default=False)
    last_reachable_check = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return f"{self.hostname} ({self.ip_address})"


class HostStatistics(models.Model):
    date = models.DateField()
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    data_center = models.ForeignKey(DataCenter, on_delete=models.CASCADE)
    host_count = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('date', 'city', 'data_center')

    def __str__(self):
        return f"{self.date} - {self.data_center}: {self.host_count} hosts"